//
//  ViewController.m
//  XMLive
//
//  Created by lxian on 2017/9/26.
//  Copyright © 2017年 BillKen. All rights reserved.
//

#import "ViewController.h"
#import "TXLiteAVSDK_Professional/TXLiveBase.h"
#import "TXLiteAVSDK_Professional/TXLivePushConfig.h"
#import "TXLiteAVSDK_Professional/TXLivePush.h"
#import "TXLiteAVSDK_Professional/TXLivePlayer.h"

#import "SVProgressHUD.h"

@interface ViewController ()<TXLivePushListener>
@property(nonatomic, nonnull, strong) TXLivePush *txLivePush;
@property(nonatomic, nonnull, strong) TXLivePlayer *txLivePlayer;
@property(nonatomic, nonnull, strong) UIView *myView;
@property (weak, nonatomic) IBOutlet UIButton *closeBtn;
@property (weak, nonatomic) IBOutlet UIButton *pushBtn;
@property (weak, nonatomic) IBOutlet UIButton *lookBtn;


@end

@implementation ViewController
{
    NSString* rtmpUrl;
    NSString *flvUrl;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 打印SDK的版本信息
//    NSLog(@"SDK Version = %@", [TXLiveBase getSDKVersionStr]);
//    [TXLiveBase setConsoleEnabled:YES];
//    [TXLiveBase setLogLevel:LOGLEVEL_DEBUG];
    [self.view insertSubview:self.myView atIndex:0];
    
    rtmpUrl = @"rtmp://11198.livepush2.myqcloud.com/live/11198_jack?bizid=11198&record_interval=10800&record=flv|hls&txSecret=7b919a3ce0248974457d646dfe9d01d1&txTime=59ca1e54";
    
    flvUrl = @"http://11198.liveplay.myqcloud.com/live/11198_rrrrrrrr.flv";
    //先注册后退消息通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    //先注册后退消息通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}

//结束推流，注意做好清理工作
- (void)stopRtmpPublish {
    [self.txLivePush stopPreview];
    [self.txLivePush stopPush];
    self.txLivePush.delegate = nil;
}
//开始推流
- (void)startRtmpPublish:(NSString *)rtmpUrl {
    [self.txLivePush startPreview:self.myView];
    self.txLivePush.delegate = self;
    [self.txLivePush startPush:rtmpUrl];
}
//开始播放
- (void)startPlay {
    [self.txLivePlayer setupVideoWidget:self.view.bounds containView:self.myView insertIndex:0];
    [self.txLivePlayer startPlay:flvUrl type:PLAY_TYPE_LIVE_FLV];
}
//停止播放
- (void)stopPlay {
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//收到通知后，调用beginBackgroundTaskWithExpirationHandler
-(void)handleEnterBackground:(NSNotification *)notification
{
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        
    }];
    [self.txLivePush pausePush];
}
//切前台处理
- (void)handleEnterForeground:(NSNotification *)notification
{
    [self.txLivePush resumePush];
}

#pragma mark - get

- (UIView *)myView {
    if (!_myView) {
        _myView = [[UIView alloc] initWithFrame:self.view.bounds];
    }
    return _myView;
}

- (TXLivePush *)txLivePush {
    if (!_txLivePush) {
        
        TXLivePushConfig* _config = [[TXLivePushConfig alloc] init];
        
        UIImage *watermark = [UIImage imageNamed:@"watermark.png"];
        _config.watermark = watermark;
        _config.watermarkPos = (CGPoint){10, 10};
        _config.pauseImg = watermark;
        
        _txLivePush = [[TXLivePush alloc] initWithConfig: _config];
        [_txLivePush setVideoQuality:VIDEO_QUALITY_HIGH_DEFINITION adjustBitrate:YES adjustResolution:YES];
        [_txLivePush setBeautyStyle:1 beautyLevel:7 whitenessLevel:7 ruddinessLevel:7];
        _txLivePush.config.enableHWAcceleration = YES;
        [_txLivePush switchCamera];
    }
    return _txLivePush;
}

- (TXLivePlayer *)txLivePlayer {
    if (!_txLivePlayer) {
        
        _txLivePlayer = [[TXLivePlayer alloc] init];
        [_txLivePlayer setupVideoWidget:[UIScreen mainScreen].bounds containView:_myView insertIndex:0];
        _txLivePlayer.enableHWAcceleration = YES;
    }
    return _txLivePlayer;
}

#pragma mark - actions
//关闭推流
- (IBAction)closeTap:(id)sender {
    if ([self.txLivePush isPublishing]) {
        [self stopRtmpPublish];
        [self.pushBtn setHidden:NO];
        [self.lookBtn setHidden:NO];
    }
    if ([self.txLivePlayer isPlaying]) {
        [self stopPlay];
        [self.pushBtn setHidden:NO];
        [self.lookBtn setHidden:NO];
    }
}
//我要直播
- (IBAction)pushTap:(UIButton *)sender {
    [self startRtmpPublish:rtmpUrl];
    [self.pushBtn setHidden:YES];
    [self.lookBtn setHidden:YES];
}
//我看直播
- (IBAction)lookTap:(UIButton *)sender {
    [self startPlay];
    [self.pushBtn setHidden:YES];
    [self.lookBtn setHidden:YES];
}

#pragma mark - TXLivePushDelegate

-(void) onPushEvent:(int)EvtID withParam:(NSDictionary*)param {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (EvtID >= 0) {
            if (EvtID == PUSH_WARNING_HW_ACCELERATION_FAIL)
            {
                _txLivePush.config.enableHWAcceleration = false;
            }
            else if (EvtID == PUSH_EVT_PUSH_BEGIN)
            {
                //该事件表示推流成功，可以通知业务server将该流置为上线状态
                
            } else if (EvtID == PUSH_WARNING_NET_BUSY) {
                [SVProgressHUD showErrorWithStatus:@"您当前的网络环境不佳，请尽快更换网络保证正常直播"];
                
            }
        } else {
            if (EvtID == PUSH_ERR_NET_DISCONNECT) {
                [SVProgressHUD showErrorWithStatus:@"网络不行 GG吧你"];
            } else if (EvtID == PUSH_ERR_OPEN_CAMERA_FAIL) {
                [SVProgressHUD showErrorWithStatus:@"摄像头权限都没有 搞毛线"];
            } else if (EvtID == PUSH_ERR_OPEN_MIC_FAIL) {
                [SVProgressHUD showErrorWithStatus:@"麦克风权限都没有 搞毛线"];
            }  else {
                if (EvtID != PUSH_ERR_VIDEO_ENCODE_FAIL) {
                    [SVProgressHUD showErrorWithStatus:@"视频编码失败"];
                }
            }
        }
        
    });
}

-(void) onNetStatus:(NSDictionary*) param {
    NSDictionary* dict = param;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        int netspeed  = [(NSNumber*)[dict valueForKey:NET_STATUS_NET_SPEED] intValue];
        int vbitrate  = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_BITRATE] intValue];
        int abitrate  = [(NSNumber*)[dict valueForKey:NET_STATUS_AUDIO_BITRATE] intValue];
        int cachesize = [(NSNumber*)[dict valueForKey:NET_STATUS_CACHE_SIZE] intValue];
        int dropsize  = [(NSNumber*)[dict valueForKey:NET_STATUS_DROP_SIZE] intValue];
        int jitter    = [(NSNumber*)[dict valueForKey:NET_STATUS_NET_JITTER] intValue];
        int fps       = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_FPS] intValue];
        int width     = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_WIDTH] intValue];
        int height    = [(NSNumber*)[dict valueForKey:NET_STATUS_VIDEO_HEIGHT] intValue];
        float cpu_usage = [(NSNumber*)[dict valueForKey:NET_STATUS_CPU_USAGE] floatValue];
        int codecCacheSize = [(NSNumber*)[dict valueForKey:NET_STATUS_CODEC_CACHE] intValue];
        int nCodecDropCnt = [(NSNumber*)[dict valueForKey:NET_STATUS_CODEC_DROP_CNT] intValue];
        NSString *serverIP = [dict valueForKey:NET_STATUS_SERVER_IP];
        
        NSString* log = [NSString stringWithFormat:@"CPU:%.1f%%\tRES:%d*%d\tSPD:%dkb/s\nJITT:%d\tFPS:%d\tARA:%dkb/s\nQUE:%d|%d\tDRP:%d|%d\tVRA:%dkb/s\nSVR:%@\t",
                         cpu_usage*100,
                         width,
                         height,
                         netspeed,
                         jitter,
                         fps,
                         abitrate,
                         codecCacheSize,
                         cachesize,
                         nCodecDropCnt,
                         dropsize,
                         vbitrate,
                         serverIP];
//        [SVProgressHUD showSuccessWithStatus:log];
    });
}
@end
